from communication.asyncClient import AsyncClient
from webpage.comm.login import quick_login
from webpage.mei.urls import register_get, register_post
from webpage.comm.AsyncSession import AsyncSession
from django.shortcuts import render
from django.http import JsonResponse
import asyncio


class TicTacToeSession(AsyncSession):
    def __init__(self, key):
        super().__init__(key)
        self.qq = ''

    async def produce(self):
        async with AsyncClient('tic_tac_toe') as client:
            while True:
                while self._input_queue.empty():
                    if self._state != AsyncSession.State.LIVE:
                        return
                    await asyncio.sleep(0.1)
                p = str(self._input_queue.get())
                ret = await client.send(p)
                self._output_queue.put(ret)
                if 'victor' in ret:
                    break
            await client.send(self.qq)


def get_next(key, p, qq):
    session = TicTacToeSession.get_session(key)
    session.qq = qq
    ret = session.consume(p)
    if ret is None:
        return {
            'victor': -1,
            'error': '等待超时，请重新开始',
        }
    if 'victor' in ret:
        session.die()
    return ret


@register_get('tic_tac_toe')
@quick_login
def tic_tac_toe_get(request):
    return render(request, 'tic_tac_toe.html')


@register_post('tic_tac_toe')
def tic_tac_toe_post(request):
    p = request.POST.get('next')
    key = request.POST.get('key')
    qq = request.user.username
    ret = get_next(key, p, qq)
    return JsonResponse(ret)
